// utils.js

function debounce (fn, delay = 300) {
  let timer = null
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}

// 暴露到全局（给原生项目用）
window.debounce = debounce

/**
 * 显示提示信息
 * @param {string} msg - 要显示的消息
 * @param {string} [type="success"] - 提示类型，默认为 "success"
 */
function DMshowToast (msg = 'success', type = 'success') {
  let toastHtml = ''
  if (type == 'success') {
    toastHtml = `<div class="dm-toast dm-toast-success">
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.01256 0.371094C4.24087 0.371094 0.372559 4.23941 0.372559 9.01109C0.372559 13.7828 4.24087 17.6511 9.01256 17.6511C13.7842 17.6511 17.6526 13.7828 17.6526 9.01109C17.6526 4.23941 13.7842 0.371094 9.01256 0.371094ZM14.0391 6.30294C14.0391 6.30294 7.71802 12.2331 7.71608 12.2348C7.57425 12.373 7.34529 12.3701 7.20704 12.2283L3.97904 9.04279C3.84079 8.90095 3.84369 8.67199 3.98553 8.53374C4.12737 8.39549 4.35632 8.39839 4.49458 8.54023L7.46698 11.4675L13.5363 5.78742C13.6782 5.64917 13.9071 5.65207 14.0454 5.79391C14.1839 5.93575 14.181 6.1647 14.0391 6.30296L14.0391 6.30294Z" fill="#CCB590"/>
</svg>
          ${msg}
      </div>`
  }
  // 将 toast 添加到页面
  $('body').append(toastHtml)

  // 获取新添加的 toast 元素
  const $toast = $('.dm-toast').last()

  // 3 秒后删除 toast
  setTimeout(function () {
    $toast.fadeOut(300, function () {
      $(this).remove()
    })
  }, 3000)
}

// 处理用户名：首尾字母，中间用*
function ProcessUserName (name) {
  if (!name || name.length <= 2) {
    return name || 'anonymous'
  }

  const firstChar = name.charAt(0)
  const lastChar = name.charAt(name.length - 1)
  const stars = '*'.repeat(name.length - 2)

  return firstChar + stars + lastChar
}

// 根据用户名生成稳定的随机颜色
function GenerateAvatar (name) {
  if (!name) return 'var(--dm-color-primary)'

  // 预定义一组好看的颜色
  const colors = [
    '#3498db',
    '#e74c3c',
    '#2ecc71',
    '#f39c12',
    '#9b59b6',
    '#1abc9c',
    '#d35400',
    '#c0392b',
    '#16a085',
    '#8e44ad',
    '#27ae60',
    '#2980b9',
    '#f1c40f',
    '#e67e22',
    '#e74c3c'
  ]

  // 根据用户名生成一个稳定的索引
  let hash = 0
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash)
  }

  const index = Math.abs(hash) % colors.length
  return colors[index]
}

// 获取字符串的首字母（支持中文）
function GetFirstCharacter (str) {
  if (!str || typeof str !== 'string') return '匿'
  // 如果是中文，取第一个字符
  if (/^[\u4e00-\u9fa5]/.test(str)) {
    return str.charAt(0)
  }
  // 如果是英文，取第一个字母（忽略数字和特殊字符）
  const match = str.match(/[a-zA-Z]/)
  return match ? match[0].toUpperCase() : str.charAt(0).toUpperCase()
}

/**
 * 渲染分页组件
 * @param {number} currentPage - 当前页码
 * @param {number} totalItems - 总数据条数
 * @param {number} pageSize - 每页显示数量
 * @param {jQuery} $renderContainer - 渲染容器jQuery对象
 * @param {function} [onPageChange] - 页码变化回调函数（可选）
 */
function RenderPagination (
  currentPage,
  totalItems,
  pageSize,
  $renderContainer,
  onPageChange
) {
  // 计算总页数
  const totalPages = Math.ceil(totalItems / pageSize)

  // 如果没有数据或只有一页，不显示分页
  if (totalPages <= 1) {
    $renderContainer.next('.page-products').remove()
    return
  }

  // 参数验证
  if (currentPage < 1 || currentPage > totalPages) {
    console.warn('当前页码超出范围，自动修正')
    currentPage = Math.max(1, Math.min(currentPage, totalPages))
  }

  // 创建分页容器
  const $pagination = $('<div class="page-products"></div>')
  const $numbers = $('<div class="page-numbers"></div>')

  // 生成左右箭头
  const $leftArrow = createPaginationArrow('left', currentPage, totalPages)
  const $rightArrow = createPaginationArrow('right', currentPage, totalPages)

  // 生成页码数字
  generatePageNumbers($numbers, currentPage, totalPages)

  // 组装分页组件
  $pagination.append($leftArrow, $numbers, $rightArrow)

  // 插入到DOM
  insertPaginationToDOM($pagination, $renderContainer)

  // 绑定点击事件
  bindPaginationEvents($pagination, currentPage, totalPages, onPageChange)

  // 返回分页信息（可选）
  return {
    currentPage,
    totalPages,
    totalItems,
    pageSize
  }
}

/**
 * 创建分页箭头
 */
function createPaginationArrow (direction, currentPage, totalPages) {
  const isLeft = direction === 'left'
  const isDisabled = isLeft ? currentPage === 1 : currentPage === totalPages
  const arrowClass = isLeft ? 'pagination-left' : 'pagination-right'
  const disabledStyle = isDisabled
    ? 'style="opacity:0.3;pointer-events:none;"'
    : ''

  const svgPath = isLeft
    ? 'M0.988692 5.82543C0.998591 5.48788 1.13512 5.15789 1.39998 4.90844L6.05289 0.526369C6.43646 0.161393 7.04713 0.179302 7.40866 0.566128C7.77402 0.953066 7.75625 1.55911 7.36895 1.92014L3.15485 5.88895L7.12913 10.0979C7.4945 10.4848 7.47673 11.0909 7.08943 11.4519C6.70201 11.8168 6.09518 11.799 5.73366 11.4121L1.34554 6.76493C1.09575 6.50039 0.978794 6.16297 0.988692 5.82543Z'
    : 'M6.79155 5.92141C6.79155 6.2591 6.66475 6.59295 6.40731 6.85005L1.88486 11.3666C1.51215 11.7427 0.901216 11.7427 0.528507 11.3666C0.151956 10.9906 0.151956 10.3843 0.528507 10.012L4.62446 5.92141L0.528507 1.83077C0.151956 1.45471 0.151956 0.848408 0.528507 0.476183C0.905058 0.100121 1.51215 0.10012 1.88486 0.476183L6.40731 4.99277C6.66475 5.24987 6.79155 5.58372 6.79155 5.92141Z'

  const svgWidth = isLeft ? 8 : 7

  return $(`
    <div class="${arrowClass} page-btn" ${disabledStyle}>
      <svg width="${svgWidth}" height="12" viewBox="0 0 ${svgWidth} 12" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="${svgPath}" fill="#586168" />
      </svg>
    </div>
  `)
}

/**
 * 生成页码数字
 */
function generatePageNumbers ($container, currentPage, totalPages) {
  // 总页数较少时显示所有页码
  if (totalPages <= 7) {
    for (let i = 1; i <= totalPages; i++) {
      appendPageNumber($container, i, i === currentPage)
    }
    return
  }

  // 首页
  if (currentPage > 2) {
    appendPageNumber($container, 1, false)
    if (currentPage > 3) {
      $container.append('<span class="page-ellipsis">...</span>')
    }
  }

  // 中间页码
  if (currentPage >= totalPages - 2) {
    // 当前页在最后3页时，显示最后5页
    for (let i = Math.max(1, totalPages - 4); i <= totalPages; i++) {
      appendPageNumber($container, i, i === currentPage)
    }
  } else {
    // 正常显示当前页及前后各1页
    const start = Math.max(1, currentPage - 1)
    const end = Math.min(totalPages, currentPage + 1)

    for (let i = start; i <= end; i++) {
      appendPageNumber($container, i, i === currentPage)
    }

    // 尾页和省略号
    if (currentPage < totalPages - 2) {
      if (currentPage < totalPages - 3) {
        $container.append('<span class="page-ellipsis">...</span>')
      }
      appendPageNumber($container, totalPages, false)
    }
  }
}

/**
 * 添加单个页码按钮
 */
function appendPageNumber ($container, page, isActive) {
  const activeClass = isActive ? 'active' : ''
  $container.append(
    `<button class="page-number ${activeClass}" data-page="${page}">${page}</button>`
  )
}

/**
 * 插入分页到DOM
 */
function insertPaginationToDOM ($pagination, $renderContainer) {
  $renderContainer.next('.page-products').remove() // 删除旧的分页
  $renderContainer.after($pagination)
}

/**
 * 绑定分页事件
 */
function bindPaginationEvents (
  $pagination,
  currentPage,
  totalPages,
  onPageChange
) {
  $pagination
    .off('click.pagination')
    .on('click.pagination', '.page-number, .page-btn', function (e) {
      e.preventDefault()

      const $target = $(this)
      let targetPage = currentPage

      if ($target.hasClass('page-number')) {
        targetPage = parseInt($target.data('page')) || currentPage
      } else if ($target.hasClass('pagination-left')) {
        targetPage = currentPage - 1
      } else if ($target.hasClass('pagination-right')) {
        targetPage = currentPage + 1
      }

      // 验证页码变化是否有效
      if (
        targetPage !== currentPage &&
        targetPage >= 1 &&
        targetPage <= totalPages
      ) {
        console.log('切换到页码:', targetPage)

        // 调用回调函数
        if (typeof onPageChange === 'function') {
          onPageChange(targetPage, currentPage)
        }

        // 触发自定义事件
        $(document).trigger('pagination:change', {
          targetPage: targetPage,
          currentPage: currentPage,
          totalPages: totalPages
        })
      }
    })
}

//判断是否是移动端
function getIsMobile () {
  return $(window).width() < 768
}

function formatSeoUrlTrim (url) {
  if (url.startsWith('/') || url.startsWith('http')) {
    return url
  }
  return '/' + url
}


// 封装表单校验函数
// 表单校验工具
var FormValidator = (function () {
  function validateForm (rules, context) {
    let allValid = true;
    const formValues = {};

    // 如果传的是 jQuery 对象，取第一个 DOM 节点
    const $context = context.jquery ? context[0] : context;

    rules.forEach(rule => {
      let value = '';

      // 自定义控件（例：评分）
      if (rule.type === 'custom' && rule.key === 'rating') {
        value = $context.querySelectorAll('.star-rating .star.selected').length || 0;
        formValues[rule.key] = value;

        if (rule.required && !value) {
          showError($context, rule.key, rule.errorMessage.required);
          allValid = false;
        } else {
          hideError($context, rule.key);
        }
        return;
      }

      // 常规 input/textarea/select
      const $elements = $context.querySelectorAll(`[name="${rule.key}"], #${rule.key}`);
      if ($elements.length === 0) {
        formValues[rule.key] = '';
        return;
      }

      const firstElement = $elements[0];
      const tagName = firstElement.tagName.toLowerCase();
      const type = (firstElement.type || '').toLowerCase();

      switch (tagName) {
        case 'input':
          if (type === 'checkbox') {
            value = handleCheckboxes($elements);
          } else if (type === 'radio') {
            const checked = $context.querySelector(`input[name="${rule.key}"]:checked`);
            value = checked ? checked.value : '';
          } else {
            value = (firstElement.value || '').trim();
          }
          break;
        case 'textarea':
          value = (firstElement.value || '').trim();
          break;
        case 'select':
          value = firstElement.value;
          break;
      }

      formValues[rule.key] = value;

      if (!validateField(rule, value, $context)) {
        allValid = false;
      }
    });

    return { valid: allValid, formParam: formValues };
  }

  function validateField (rule, value, $context) {
    if (rule.required && (!value || (Array.isArray(value) && value.length === 0))) {
      showError($context, rule.key, rule.errorMessage.required);
      return false;
    }
    if (rule.maxLength && value.length > rule.maxLength) {
      showError($context, rule.key, rule.errorMessage.maxLength);
      return false;
    }
    if (rule.regex && value && !rule.regex.test(value)) {
      showError($context, rule.key, rule.errorMessage.regex);
      return false;
    }
    hideError($context, rule.key);
    return true;
  }

  function handleCheckboxes ($elements) {
    if ($elements.length > 1) {
      return Array.from($elements)
        .filter(el => el.checked)
        .map(el => el.value);
    } else {
      return $elements[0].checked;
    }
  }

  function showError ($context, key, message) {
    const input = $context.querySelector(`#${key}, [name="${key}"]`);
    if (!input) return;
    const error = input.closest('.form-item').querySelector('.error-message');
    if (error) {
      error.textContent = message;
      error.classList.add('show');
    }
  }

  function hideError ($context, key) {
    const input = $context.querySelector(`#${key}, [name="${key}"]`);
    if (!input) return;
    const error = input.closest('.form-item').querySelector('.error-message');
    if (error) {
      error.classList.remove('show');
    }
  }

  return {
    validateForm: validateForm
  };
})();
